import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {DepartmentService} from '../../service/department.service';
import {DepartmentQueryForm} from '../../types/req/DepartmentQueryForm';
import {SharedModule} from '../shared.module';
import {Department} from '../../types/resp/Department';
import {Page} from '../../types/page';
import {DepartmentAddComponent} from './department-add.component';
import {DepartmentViewComponent} from './department-view.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {EnterpriseSelectorComponent} from '../enterprise/enterprise-selector.component';
import {DepartmentSelectorComponent} from '../department/department-selector.component';
import { exportToExcel } from '../../utils/exportUtil'


@Component({
  selector: 'department-list',
  imports: [
    EnterpriseSelectorComponent,
    DepartmentSelectorComponent,
    DepartmentAddComponent,
    DepartmentViewComponent,
    SharedModule
  ],
  templateUrl: './department-list.component.html',
  standalone: true
})
export class DepartmentListComponent implements OnInit {
  searchForm!: FormGroup;
  searchLoading: boolean = false
  listOfData: Department[] = [];
  total: number = 0

  @ViewChild(EnterpriseSelectorComponent, { static: false }) enterpriseSelectorComponent!: EnterpriseSelectorComponent;
  @ViewChild(DepartmentSelectorComponent, { static: false }) departmentSelectorComponent!: DepartmentSelectorComponent;
  @ViewChild(DepartmentAddComponent, { static: false }) departmentAddComponent!: DepartmentAddComponent;
  @ViewChild(DepartmentViewComponent, { static: false }) departmentViewComponent!: DepartmentViewComponent;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private departmentService: DepartmentService,
    private modal: NzModalService
  ) {}

  ngOnInit(): void {
    this.searchForm = this.fb.group({
      enterpriseId: [0],
      enterpriseName: [''],
      departmentName: [''],
      parentDepartmentId: [0],
      parentDepartmentName: [''],
    })
    this.onSearch()
  }

  onReset() {
    this.searchForm.reset()
  }

  onSearch() {
    try {
      this.searchLoading = true
      this.departmentService.find(new DepartmentQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          const page: Page<Department> | undefined = resp.data
          if (page && page.list.length > 0) {
            this.listOfData = page.list
            this.total = page.total
          }
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onAdd() {
    this.departmentAddComponent.display(0)
  }

  onExport() {
    try {
      const headers = ['企业名称','部门名称','部门描述','上级部门名称',]
      this.searchLoading = true
      this.departmentService.find(new DepartmentQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1 || !resp.data || resp.data.list.length < 1) {
            this.message.error('无数据导出')
            return
          }
          const exportData = []
          for (const d of resp.data.list) {
            exportData.push([d.enterpriseName,d.departmentName,d.departmentDescription,d.parentDepartmentName])
          }
          exportToExcel(headers, exportData)
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  editRow(id: number) {
    this.departmentAddComponent.display(id)
  }

  delRow(id: number) {
    this.modal.confirm({
      nzTitle: '<i>删除提示</i>',
      nzContent: '<b>确定要删除吗?</b>',
      nzOnOk: () => {
        this.departmentService.del(id).subscribe({
          next: (resp) => {
            if (resp && resp.code === 1) {
              this.message.success('删除成功!')
              this.onSearch()
            } else {
              this.message.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
            }
          },
          complete: () => {
            this.searchLoading = false
          }
        })
      }
    });
  }

  detailRow(record: Department) {
    this.departmentViewComponent.display(record)
  }

  findEnterprise() {
    this.enterpriseSelectorComponent.display()
  }

  handleEnterpriseSelectedEvent(selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) {
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      this.searchForm.patchValue(selectedEnterprise);
    }
  }

  findDepartment() {
    this.departmentSelectorComponent.display()
  }

  handleDepartmentSelectedEvent(selectedDepartment: { parentDepartmentId?: number; parentDepartmentName?: string; }) {
    if (selectedDepartment && 'parentDepartmentId' in selectedDepartment) {
      this.searchForm.patchValue(selectedDepartment);
    }
  }

  onAdded(addedFlag: boolean) {
    if (addedFlag) {
      this.onSearch()
    }
  }
}
